package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties properties;

    @Override
    public User loginWeChat(UserLoginDTO dto) {


        //1.组装参数，doGet(url,map<string,string>)调用微信登录接口获取openid
        HashMap map = new HashMap();
        map.put("appid",properties.getAppid());
        map.put("secret",properties.getSecret());
        //用户传来的临时码
        map.put("js_code",dto.getCode());
        //固定的
        map.put("grant_type","authorization_code");
        //返回一个json格式的result对象
        String jsonResult = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        //解析json为对象
        JSONObject jsonObject = JSON.parseObject(jsonResult);
        //获取第三方返回的openid
        String openid = jsonObject.getString("openid");
        if(null == openid || "".equals(openid)){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //2.根据openid查询user表，判断用户是否存在
        User user = userMapper.getUserByOpenId(openid);

        //3.如果返回对象为空则表示不存在，则需要新建一个用户
        if(null == user){
            User user1 = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.insert(user1);
            return user1;
        }

        //4.如果不为空则直接返回
        return user;
    }
}
